# -*- coding: utf-8 -*-
# @日期 : 2022/1/27 0027
# @作者 : sean
# @版本 : v1.0
# @功能 :
import os

import requests
import csv

if __name__ == '__main__':


    goods_id=input('输入商品id')

    # 创建目录
    #if os.path.exists(f"./xmh_goods_pic/{goods_id}/") != True:
    os.makedirs(f'./xmh_goods_pic/{goods_id}/')

    url=f'https://www.xinminghui.com/v1/goods/index?id={goods_id}'
    page_data=requests.get(url)
    print(page_data.json()['payload']['orderGoods'])
    orderGoods=page_data.json()['payload']['orderGoods']

    #存储商品id
    orderGoods_list=[]
    for i in orderGoods:
        orderGoods_list.append(i["goods_id"])


    #遍历商品id 返回商品信息
    f = open('xmh_goods.csv', mode = 'w',encoding = 'utf-8')
    csv_writer = csv.writer(f)
    for j in orderGoods_list:
        goods_url=f'https://www.xinminghui.com/v1/goods/index?id={j}'
        get_data=requests.get(goods_url)
        goods_data=get_data.json()['payload']['goods']
        dic={
            #'goods_name':goods_data["goods_name"],
            'goods_id':j,
             'goods_img': goods_data["goods_origin"],
             }
        #把商品名和图片地址写入csv文件
        csv_writer.writerow(dic.values())
    f.close()

    #读取csv文件
    with open('xmh_goods.csv', 'r') as f:
        reader = csv.reader(f)
        result = list(reader)

        headers={
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69'
        }


        for goods in result:
            if len(goods) >0:
                goods_nam=goods[0]
                goods_url=goods[1]

                # requests访问图片地址返回二进制数据
                imag_data = requests.get(url = goods_url,headers=headers).content
                # wb 写二进制
                with open(f'./xmh_goods_pic/{goods_id}/{goods_nam}.jpg', 'wb') as fp:
                    fp.write(imag_data)


    print('over!')